import os
import time

import requests

from common import wrapper
from common.db import get_db
from common.db.crud import taobao as taobao_crud

from tasks import base


class CommonTaobao(base.BaseTask):
    def __init__(self, android_ip):
        self.order = taobao_crud.get_order(self.db_session, android_ip).to_obj
        self.android_ip = str(self.order.android_ip)
        self.order_id = self.order.order_id
        super().__init__(self.android_ip, self.order_id)
        self.log_msg(self.order)
        self._current_page_only_text = []

    @property
    def db_session(self):
        return next(get_db())

    @property
    def analysis_dict(self):
        raise NotImplementedError

    def update_db_flag(self, dict_value):
        self.log_msg('update db_flag={}'.format(dict_value))
        taobao_crud.update_order(self.db_session, self.android_ip, dict_value)

    def get_current_page_xml(self):
        self.current_page_attrib = self.u2.get_page_attrib(only_text=True, only_package=['com.taobao.taobao'])
        return self.current_page_attrib

    def get_current_page_only_text(self):
        time.sleep(1)
        page_value = self.get_current_page_xml()
        self._current_page_only_text = [i['only_text'] for i in page_value]

    @property
    def current_page_only_text(self):
        if not self._current_page_only_text:
            self.get_current_page_only_text()
        return self._current_page_only_text

    def what_current_page(self):
        self.get_current_page_only_text()
        page_text_list = self.current_page_only_text
        for name, text_list in self.analysis_dict.items():
            for text in text_list:
                if isinstance(text, list):
                    # for i in text:
                    #     if i in page_text_list:
                    #         return
                    # else:
                    #     break
                    if not set(text) & set(page_text_list):
                        break
                elif text not in page_text_list:
                    break
            else:
                self.log_msg('find is {}'.format(name))
                return name
        else:
            err_msg = "can't identify current page, current text={}".format(page_text_list)
            self.log_msg(err_msg)

    def get_code(self, timeout=5 * 60):
        times = 0
        start_time = time.perf_counter()
        taobao_crud.update_order(self.db_session, self.android_ip, dict(need_phone_code=True, phone_code=''))
        user_phone = self.order.user_phone
        while True:
            use_time = int(time.perf_counter() - start_time)
            if use_time > timeout:
                self.raise_exception('Getting SMS verification code timed out, 300s')
                break
            times += 1
            self.log_msg('No.{}查询{}的短信校验码,剩余{}秒'.format(times, self, user_phone, timeout - use_time))
            self.order = taobao_crud.get_order(self.db_session, self.android_ip).to_obj
            if phone_code := self.order.phone_code:
                self.log_msg('获取到{}的短信校验码={}'.format(user_phone, phone_code))
                taobao_crud.update_order(self.db_session, self.android_ip, dict(need_phone_code=False, phone_code=''))
                return phone_code
            time.sleep(2)

    def goto_main_activity(self, delay_time=1):
        self.u2.start_activity("com.taobao.taobao", 'com.taobao.tao.TBMainActivity')
        time.sleep(delay_time)
